# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import csv
import os

from itemadapter import ItemAdapter


class SecondprojectPipeline:
    def open_spider(self, spider):
        self.save_path = os.getcwd() + "/优信二手车/"
        if not os.path.exists(self.save_path):  # 判断文件夹是否存在
            os.makedirs(self.save_path)  # 没有就创建文件夹

    def process_item(self, item, spider):
        type_ = item.get("type")
        with open(self.save_path + type_ + ".csv", "a") as f:
            # 创建一个csv的DictWriter对象，这样才能够将写入csv格式数据到这个文件
            f_csv = csv.DictWriter(f, ['title', 'year', 'price', 'time'])
            # 写入多行行（当做数据）
            item.pop("type")  # 删除type 这个key-value
            f_csv.writerows([item])
            print("保存信息到%s.csv....ok")
        return item
